<?php
class User_child_model extends CI_Model{

	/**
	 * 获取孩子信息
	 * @param  [type] $child_id [description]
	 * @return [type]           [description]
	 */
	function get_info_by_id($child_id){
		$sql = "SELECT * FROM {$this->db->dbprefix}user_childrens WHERE id = $child_id";
		return $this->db->query($sql)->row_array();
	}

	function get_habit_count($child_id){
		$sql = "SELECT COUNT(0) as habit_total FROM {$this->db->dbprefix}tasks  WHERE child_id = $child_id";
		return $this->db->query($sql)->row_array()['habit_total'];
	}

	function get_habit_by_child($child_id){
		$sql = "SELECT t.*,trs.id as statistics_id,trs.total_stars,trs.first_time,trs.last_time FROM {$this->db->dbprefix}tasks t ";
		$sql .= "LEFT JOIN {$this->db->dbprefix}user_children_task_type_statistics trs on trs.task_id = t.id ";
		$sql .= "LEFT JOIN {$this->db->dbprefix}user_childrens AS uc ON(uc.id=t.child_id) ";
		$sql .= "WHERE t.child_id = '{$child_id}' AND uc.id > 0";
		return $this->db->query($sql)->result_array();
	}

	function get_habit_record($habit_id,$limit=3){
		$sql = "SELECT * FROM {$this->db->dbprefix}task_records 
		WHERE task_id = $habit_id ORDER BY id DESC LIMIT $limit";
		return $this->db->query($sql)->result_array();
	}

	function get_habit_record_list($habit_id, $limit = 0, $offset = 10){
		$sql = "SELECT SQL_CALC_FOUND_ROWS *, FROM_UNIXTIME(time, '%Y-%m-%d') AS date FROM {$this->db->dbprefix}task_records WHERE task_id = $habit_id AND stars > 0 ORDER BY id DESC LIMIT $limit, $offset";
		$result = $this->db->query($sql)->result_array();
		$row_num =  $this->db->query('SELECT FOUND_ROWS() as row_num;')->row_array();
		return array("count" => $row_num['row_num'], "list" => $result);
	}

	function get_habit_type_info($habit_id){
		$sql = "SELECT tt.image,tt.name,tt.id FROM {$this->db->dbprefix}tasks AS t ";
		$sql .= "LEFT JOIN {$this->db->dbprefix}task_types AS tt ON(tt.id=t.task_type_id) WHERE t.id='{$habit_id}'";
		return $this->db->query($sql)->row_array();
	}
}